<template>
  <div class="editContainer">
    <div ref="mindMapContainer" class="mindMapContainer" />
    <Count v-if="!isZenMode" :time="time" />
    <Navigator :mind-map="mindMap" />
    <NavigatorToolbar v-if="!isZenMode" :mind-map="mindMap" />
    <Outline :mind-map="mindMap" />
    <Styles v-if="!isZenMode" />
    <BaseStyle :data="mindMapData" :mind-map="mindMap" />
    <Theme :mind-map="mindMap" />
    <Structure :mind-map="mindMap" />
    <ShortcutKey />
    <Contextmenu v-if="mindMap" :mind-map="mindMap" />
    <RichTextToolbar v-if="mindMap" :mind-map="mindMap" />
    <NodeIconSidebar v-if="mindMap" :mind-map="mindMap" />
    <NodeNoteContentShow v-if="mindMap" :mind-map="mindMap" />
    <NodeImgPreview v-if="mindMap" :mind-map="mindMap" />
    <SidebarTrigger v-if="!isZenMode" />
    <Search v-if="mindMap" :mind-map="mindMap" />
  </div>
</template>

<script>
import MindMap from 'simple-mind-map'
import MiniMap from 'simple-mind-map/src/plugins/MiniMap.js'
import Watermark from 'simple-mind-map/src/plugins/Watermark.js'
import KeyboardNavigation from 'simple-mind-map/src/plugins/KeyboardNavigation.js'
import ExportPDF from 'simple-mind-map/src/plugins/ExportPDF.js'
import ExportXMind from 'simple-mind-map/src/plugins/ExportXMind.js'
import Export from 'simple-mind-map/src/plugins/Export.js'
import Drag from 'simple-mind-map/src/plugins/Drag.js'
import Select from 'simple-mind-map/src/plugins/Select.js'
import RichText from 'simple-mind-map/src/plugins/RichText.js'
import AssociativeLine from 'simple-mind-map/src/plugins/AssociativeLine.js'
import TouchEvent from 'simple-mind-map/src/plugins/TouchEvent.js'
import NodeImgAdjust from 'simple-mind-map/src/plugins/NodeImgAdjust.js'
import SearchPlugin from 'simple-mind-map/src/plugins/Search.js'
import Outline from './Outline'
import Styles from './Style'
import BaseStyle from './BaseStyle'
import Theme from './Theme'
import Structure from './Structure'
import Count from './Count'
import NavigatorToolbar from './NavigatorToolbar'
import ShortcutKey from './ShortcutKey'
import Contextmenu from './Contextmenu'
import RichTextToolbar from './RichTextToolbar'
import NodeNoteContentShow from './NodeNoteContentShow.vue'
import { getData, storeData, storeConfig } from '@/components/SimpleMindMap/api'
import Navigator from './Navigator.vue'
import NodeImgPreview from './NodeImgPreview.vue'
import SidebarTrigger from './SidebarTrigger.vue'
import NodeIconSidebar from './NodeIconSidebar.vue'
import Search from './Search.vue'
// import Vue from 'vue'
// import CustomNodeContent from './CustomNodeContent.vue'
import icon from '@/components/SimpleMindMap/config/icon'
// import Color from './Color.vue'
// import router from '../../../router'
// import store from '../../../store'
// import i18n from '../i18n'
import { getDealListLite } from '@/api/base/deal/dealBase'
import customThemeList from '@/components/SimpleMindMap/customThemes'
// 注册自定义主题
customThemeList.forEach(item => {
  MindMap.defineTheme(item.value, item.theme)
})

// 注册插件
MindMap.usePlugin(MiniMap)
  .usePlugin(Watermark)
  .usePlugin(Drag)
  .usePlugin(KeyboardNavigation)
  .usePlugin(ExportPDF)
  .usePlugin(ExportXMind)
  .usePlugin(Export)
  .usePlugin(Select)
  .usePlugin(AssociativeLine)
  .usePlugin(NodeImgAdjust)
  .usePlugin(SearchPlugin)
  .usePlugin(TouchEvent)

/**
 * @Desc: 编辑区域
 */
export default {
  name: 'Edit',
  components: {
    Outline,
    Styles,
    BaseStyle,
    Theme,
    Structure,
    Count,
    NavigatorToolbar,
    ShortcutKey,
    Contextmenu,
    RichTextToolbar,
    NodeNoteContentShow,
    Navigator,
    NodeImgPreview,
    SidebarTrigger,
    NodeIconSidebar,
    Search
  },
  props: {
    /* 编辑器的内容 */
    value: {
      type: Object,
      default: () => {}
    },
    mode: {
      type: String,
      default: 'edit'
    },
    /* 只读 */
    readOnly: {
      type: Boolean,
      default: false
    },
    time: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      mindMap: null,
      mindMapData: null,
      prevImg: '',
      openTest: false,
      isAutoSaveData: false
    }
  },
  computed: {
    isZenMode() {
      if (this.mode === 'readonly') {
          return true
      }
      return this.$store.state.SimpleMindMap.localConfig.isZenMode
    },
    openNodeRichText() { return this.$store.state.SimpleMindMap.localConfig.openNodeRichText },
    useLeftKeySelectionRightKeyDrag() { return this.$store.state.SimpleMindMap.localConfig.useLeftKeySelectionRightKeyDrag }
  },
  watch: {
    openNodeRichText() {
      if (this.openNodeRichText) {
        this.addRichTextPlugin()
      } else {
        this.removeRichTextPlugin()
      }
    }
  },
  mounted() {
    // this.showNewFeatureInfo()
    this.getData()
    this.init()
    this.$bus.$on('execCommand', this.execCommand)
    this.$bus.$emit('execCommand', 'UNEXPAND_ALL', true)
    this.$bus.$on('paddingChange', this.onPaddingChange)
    this.$bus.$on('export', this.export)
    this.$bus.$on('setData', this.setData)
    this.$bus.$on('startTextEdit', () => {
      this.mindMap.renderer.startTextEdit()
    })
    this.$bus.$on('endTextEdit', () => {
      this.mindMap.renderer.endTextEdit()
    })
    this.$bus.$on('createAssociativeLine', () => {
      this.mindMap.associativeLine.createLineFromActiveNode()
    })
    window.addEventListener('resize', () => {
      this.mindMap.resize()
    })
    if (this.mode === 'readonly') {
      this.mindMap.setMode('readonly')
    }
  },
  methods: {
    getData() {
      const storeData = this.value !== null ? this.value : getData()
      localStorage.setItem('SIMPLE_MIND_MAP_DATA', storeData)
      this.mindMapData = storeData
    },
    bindSaveEvent() {
      if (this.openTest) {
        return
      }
      this.$bus.$on('node_tree_render_end', () => { // 节点树渲染完毕事件
        this.isAutoSaveData = true
      })
      this.$bus.$on('data_change', data => {
        if (this.isAutoSaveData) {
          storeData(data, this.mindMapData)
          if (this.mode !== 'readonly') {
            this.$bus.$emit('autoSaveData')
          }
        }
      })
      this.$bus.$on('view_data_change', data => { // 视图变化数据，比如拖动或缩放时会触发
        this.$bus.$emit('hideNoteContent')
        storeConfig({
          view: data
        }, this.mindMapData)
      })
    },
    manualSave() {
      if (this.openTest) {
        return
      }
      const data = this.mindMap.getData(true)
      storeConfig(data)
    },

    /**
     * @Desc: 初始化
     */
    init() {
      const { root, layout, view, config, theme } = this.mindMapData
      console.log(theme, 'themethemetheme')
      this.mindMap = new MindMap({
        el: this.$refs.mindMapContainer,
        data: root,
        layout: layout,
        theme: theme.template,
        themeConfig: theme.config,
        viewData: view,
        nodeTextEditZIndex: 1000,
        nodeNoteTooltipZIndex: 1000,
        mousewheelAction: 'zoom',
        customNoteContentShow: {
          show: (content, left, top) => {
            this.$bus.$emit('showNoteContent', content, left, top)
          },
          hide: () => {
            // this.$bus.$emit('hideNoteContent')
          }
        },
        ...(config || {}),
        iconList: icon,
        useLeftKeySelectionRightKeyDrag: this.useLeftKeySelectionRightKeyDrag
      })

      // console.log('this.mindMap', this.mindMap)
      if (this.openNodeRichText) this.addRichTextPlugin()
      this.mindMap.keyCommand.addShortcut('Control+s', () => {
        this.manualSave()
      })
      // 转发事件
      ;[
        'node_active',
        'data_change',
        'view_data_change',
        'back_forward',
        'node_contextmenu',
        'node_click',
        'draw_click',
        'expand_btn_click',
        'svg_mousedown',
        'mouseup',
        'mode_change',
        'node_tree_render_end',
        'rich_text_selection_change',
        'transforming-dom-to-images',
        'generalization_node_contextmenu',
        'painter_start',
        'painter_end',
        'scrollbar_change'
      ].forEach(event => {
        this.mindMap.on(event, (...args) => {
          this.$bus.$emit(event, ...args)
        })
      })
      this.bindSaveEvent()
    },

    /**
     * @Desc: 动态设置思维导图数据
     */
    setData(data) {
      if (data.root) {
        this.mindMap.setFullData(data)
      } else {
        this.mindMap.setData(data)
      }
      this.mindMap.view.reset()
      this.manualSave()
    },

    /**
     * @Desc: 重新渲染
     */
    reRender() {
      this.mindMap.reRender()
    },

    /**
     * @Desc: 执行命令
     */
    execCommand(...args) {
      this.mindMap.execCommand(...args)
    },

    /**
     * @Desc: 导出
     */
    async export(...args) {
      const mindMapData = this.mindMap.getData(true)
      this.rootData(mindMapData.root, 'export')
      setTimeout(() => {
        this.setData(mindMapData)
        // console.log(this.mindMapData, 2222)
        try {
          this.mindMap.export(...args)
          setTimeout(() => {
            this.rootData(mindMapData.root)
            this.setData(mindMapData)
          }, 1000)
        } catch (error) {
          console.log(error)
        }
      }, 1000)
    },
    async rootData(node, key) {
      if (node.data && node.data?.deals !== undefined) {
        var note = ''
        var _note = node.data.note || '\n'
        if (_note && _note !== '\n') {
          var noteArr = _note.split('\n')
          if (noteArr && noteArr.length > 0) {
            _note = noteArr[0] + '\n'
          }
        }
        var deals = node.data.deals || []
        // 查看最新项目名称
        var dealIdList = deals.map(v => v.id)
        if (dealIdList && dealIdList.length > 0) {
            var queryParams = {
              dealName: undefined,
              pageNum: 1,
              pageSize: 20,
              personCharge: undefined,
              idsStr: dealIdList.join(',')
            }
            await getDealListLite(queryParams).then(response => {
              response.rows.forEach(ele => {
                note += ele.dealName + '\n'
              })
            })
        }
        if (key === 'export') {
          node.data.note = _note + note
        } else {
          node.data.note = node.data.newNote
        }
      }
      if (node.children) {
        node.children.forEach(e => {
          this.rootData(e, key)
        })
      }
    },

    // 修改导出内边距
    onPaddingChange(data) {
      this.mindMap.updateConfig(data)
    },

    // 显示新特性提示
    showNewFeatureInfo() {
      const showed = localStorage.getItem('SIMPLE_MIND_MAP_NEW_FEATURE_TIP_1')
      if (!showed) {
        this.$notify.info({
          title: this.$t('edit.newFeatureNoticeTitle'),
          message: this.$t('edit.newFeatureNoticeMessage'),
          duration: 0,
          onClose: () => {
            localStorage.setItem('SIMPLE_MIND_MAP_NEW_FEATURE_TIP_1', true)
          }
        })
      }
    },

    // 加载节点富文本编辑插件
    addRichTextPlugin() {
      if (!this.mindMap) return
      this.mindMap.addPlugin(RichText)
    },

    // 移除节点富文本编辑插件
    removeRichTextPlugin() {
      this.mindMap.removePlugin(RichText)
    }
  }
}
</script>

<style lang="scss" scoped>
.editContainer {
  height: 100%;
  width: 100%;

  .mindMapContainer {
    height: 100%;
    width: 100%;
  }
}
/deep/.smm-node{
  .smm-expand-btn{
    circle{
      stroke: #50BEFE!important;
      stroke-width: 2;
    }
    text{
      fill: #50BEFE!important;
    }
    .icon{
      fill: #50BEFE!important;
    }
  }
}
</style>
